<?php

declare(strict_types=1);

namespace App\Job;

use App\Helpers\ImUtil;
use App\Model\Service\GiftService;
use App\Model\Setting\SettingAutoMsg;
use App\Model\User;
use Hyperf\AsyncQueue\Job;

class SendSysgiftJob extends Job
{
    /**
     * 参数
     */
    public $params;

    const TYPE_ONLINE_PUSH = 1;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 1;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $userId = $this->params['user_id'] ?? 0;
        if (!$userId) return;
        $pushNum = $this->params['push_num'] ?? 1;
        $batchNo = $this->params['batch_no'] ?? 1;

        //礼物
        $giftService = new GiftService();
        $ret = $giftService->proccessSysGift($userId, [
            'host_cate' => 0,
            'gift_id' => 25,
            'gift_num' => env('USER_SYSGIFT_MAX_NUM', 50000),
            'single_gift_num' => $pushNum,
            'gift_expire_time' => env('USER_SYSGIFT_EXP_TIME', 120),
        ]);
        $pushHostIds = $ret['push_uids'] ?? [];
        // if (empty($pushHostIds)) return;
        //文字消息
        // $msgRet = $this->sendTextMsg($userId, $pushHostIds);
        log_user_result($userId, "BatchNo:{$batchNo}==PushHosts:" . json_encode($pushHostIds));
        return;
    }

    /**
     * 发送文字消息
     */
    function sendTextMsg($userId, $hostIds = [])
    {
        if (empty($hostIds)) return false;
        $msgs = SettingAutoMsg::getList(SettingAutoMsg::TYPE_SYS, 1);
        $content = $msgs[array_rand($msgs)];
        $uids = array_merge($hostIds, [$userId]);
        $imAccounts = User::getImAccounts($uids);
        $fromAccount = $imAccounts[$userId];
        unset($imAccounts[$userId]);
        foreach ($imAccounts as $imAccount) {
            $content = $msgs[array_rand($msgs)];
            $content = "【缘分牵线】" . $content;
            $ret = ImUtil::sendTextMsg($imAccount, $content, $fromAccount, 2);
        }
        return $ret;
    }
}
